<script setup lang="ts">
import { useRouter } from 'vue-router'
import Cookies from 'js-cookie'
import { ElMessage, ElMessageBox } from 'element-plus'
import InfoDialog from './InfoDialog.vue'

import { LOGIN_URL } from '@/constants'

const router = useRouter()
const accountName = Cookies.get('accountName')
const accountType = Cookies.get('accountType')
const proxyName = Cookies.get('proxyName')
const name = proxyName || accountName

const infoVisible = ref(false)
// 退出登录
function logout() {
  ElMessageBox.confirm('您是否确认退出登录?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 3.重定向到登陆页
    router.replace(LOGIN_URL)
    ElMessage.success('退出登录成功！')
  })
}

async function resetAccount() {
  await useRequest('ProxyChangeAccount', )
  Cookies.remove('proxyName')
  ElNotification({
    type: 'success',
    message: `帐户还原成功`,
  })
  nextTick(() => {
    window.location.reload()
  })
}
const accountDialog = reactive({
  visible: false,
  title: '切换账户',
})

/** 切代理账户 */
async function changeDone({ accountUuid }) {
  if (!accountUuid)
    return
  const { success, accountName } = await useRequest('ProxyChangeAccount', {
    changeAccountUuid: accountUuid,
  }) as any
  if (success) {
    Cookies.set('proxyName', accountName)
    ElNotification({
      type: 'success',
      message: `代理帐户切换成功`,
    })
    nextTick(() => {
      window.location.reload()
    })
  }
}
</script>

<template>
  <el-dropdown>
    <div class="flex-center text-blue-500">
      <p class="max-w-50 w-full truncate text-center">
        {{ name }}
      </p>
      <i-ri:arrow-down-s-fill />
    </div>

    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="infoVisible = true">
          <el-icon><IEpUser /></el-icon>账户信息
        </el-dropdown-item>
        <template v-if="accountType === 'Proxy'">
          <el-dropdown-item v-if="proxyName" @click="resetAccount">
            <el-icon><IEpSwitchButton /></el-icon>还原账户
          </el-dropdown-item>
          <el-dropdown-item v-else @click="accountDialog.visible = true">
            <el-icon><IEpSwitch /></el-icon> 切换账户
          </el-dropdown-item>
        </template>
        <el-dropdown-item divided @click="logout">
          <el-icon><IEpSwitchButton /></el-icon> 退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <!-- infoDialog -->
  <InfoDialog v-model="infoVisible" />
  <AccountDialog v-model="accountDialog" @done="changeDone" />
</template>
